<?php

namespace app\zmt\controller;
use think\facade\Db;
use app\zmt\model\GoodsModel;
use app\zmt\validate\GoodsValidate;
use cmf\controller\AdminBaseController;

class GoodsController extends AdminBaseController
{
    public function index()
    {
        // 获取搜索关键字
        $keyword = input('get.keyword', '');
        $where = [];
        if ($keyword) {
            $where[] = ['title|id', 'like', '%' . $keyword . '%'];
        }

        // 查询所有商品并传递给视图
        $goods = GoodsModel::where($where)
            ->order("list_order", 'desc')
            ->paginate(10);

        $page = $goods->render();

        $this->assign('goodsList', $goods);
        $this->assign('typeMap', $this->typeMap);
        $this->assign('statusMap', $this->statusMap);
        $this->assign('page', $page);
        return $this->fetch();
    }

    protected $typeMap = [
        0 => '自营',
        1 => '旗舰店',
        2 => '官方旗舰店',
    ];

    protected $statusMap = [
        0 => '已缺货',
        1 => '上架中',
        2 => '下架',
    ];

    public function add()
    {
        return $this->fetch();
    }

    public function addPost()
    {
            $data = input('post.');
            $data['images'] =  implode(',', $data['images']);
            if (GoodsModel::create($data)) {
                $this->success('添加成功', url('goods/index'));
            } else {
                $this->error('添加失败');
            }
    }

    public function changeStatus()
    {
        $id = input('param.id', 0, 'intval');
        $goods = GoodsModel::find($id);

        if ($goods) {
            // 切换状态：缺货->上架->下架->缺货
            if ($goods->switch == 0) {
                $goods->switch = 1;
            } elseif ($goods->switch == 1) {
                $goods->switch = 2;
            } else {
                $goods->switch = 0;
            }

            if ($goods->save()) {
                $this->success('状态切换成功', 'Goods/index');
            } else {
                $this->error('状态切换失败', 'Goods/index');
            }
        } else {
            $this->error('商品不存在', 'Goods/index');
        }
    }

//营店类型切换
    public function changeStatustwo()
    {
        $id = input('id', 0, 'intval');
        $goods = goodsModel::find($id);
        if ($goods) {
            // 切换状态：自营->旗舰店->非自营->自营
            if ($goods->type == 0) {
                $goods->type = 1;
            } elseif ($goods->type == 1) {
                $goods->type = 2;
            } else {
                $goods->type = 0;
            }
            if ($goods->save()) {
                $this->success('状态切换成功', 'goods/index');
            } else {
                $this->error('状态切换失败', 'goods/index');
            }
        } else {
            $this->error('商品不存在', 'goods/index');
        }
    }


    public function edit($id)
    {
        $goods = GoodsModel::find($id);
        if (!$goods) {
            $this->error('商品不存在');
        }

        $this->assign('goods', $goods);
        return $this->fetch();
    }

    public function editPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = new GoodsValidate();
            if (!$validate->scene('editPost')->check($data)) {
                $this->error($validate->getError());
            }

            $goods = GoodsModel::find($data['id']);
            if (!$goods) {
                $this->error('商品不存在');
            }

            $goods->title = $data['title'];
            $goods->image = $data['image'];
            $goods->price = $data['price'];
            $goods->after = $data['after'];
            $goods->sales = $data['sales'];
            $goods->switch = isset($data['switch']) ? $data['switch'] : 0;
            $goods->type = $data['type'];
            $goods->update_time = date('Y-m-d H:i:s');

            if ($goods->save()) {
                $this->success('编辑成功', url('goods/index'));
            } else {
                $this->error('编辑失败');
            }
        }
    }

    public function delete($id)
    {
        $goods = GoodsModel::find($id);
        if (!$goods) {
            $this->error('商品不存在');
        }

        if ($goods->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function order()
    {
        parent::listOrders(new GoodsModel());
        $this->success('排序成功');
    }

    // 1打开配置页面
    public function setGoodsAttr() {
        $goodsId = input('goods_id');
        $list = \think\facade\Db::name('guige')
            ->where('goods_id', $goodsId)
            ->select();
        $this->assign('goods_id', $goodsId);
        return $this->fetch('add_goods_attr', ['list' => $list]);
    }
    // 配置提交
    public function setGoodsAttrPost() {
        $attrs = input('post.attr');
        $goodsId = input('post.goods_id');
//        if(count($attrs)-1 < 1){
//            $this->error('请至少配置一个属性！');
//        }
        Db::name('guige')
            ->where('goods_id', $goodsId)
            ->delete();
        $insert_data = [];
        foreach($attrs as $attr){
            $insert_data[] = [
                'goods_id' => $goodsId,
               'name'=>$attr['name']
            ];
        }
        \think\facade\Db::name('guige')->insertAll($insert_data);
        $this->success('保存成功');
    }


    //设置属性
    public function setGoodsAttrValue()
    {
        $goodsId = input('goods_id');
        $this->assign('goods_id', $goodsId);
        return $this->fetch('add_goods_attr_value');
    }
    public function getGoodsAttr2()
    {
        $goodsId = input('goods_id');
        $attrs = \think\facade\Db::name('guige')
            ->where('goods_id', $goodsId)
            ->select();
        return json(['code'=>1,'msg'=>'商品属性','data'=>$attrs]);
    }



    public function GetGoodsAttrValue()
    {
        $goodsId = input('goods_id');
        $attrs = \think\facade\Db::name('guige')
            ->where('goods_id', $goodsId)
            ->select();
        return json(['code'=>1,'msg'=>'商品属性','data'=>$attrs]);
    }

    public function setGoodsAttrValuePost()
    {
        $data = input('post.form');
//        if(count($attrs)-1 < 1){
//            $this->error('请至少配置一个属性！');
//        }
        $insert_data = [];
        foreach($data as $attr){
            $insert_data[] = [
                'value' => $attr['attr_value'],
                'details_id' => $attr['attr']
            ];
        }
        $insert = \think\facade\Db::name('goods_value')->insertAll($insert_data);
        if ($insert){
            return json(['code'=>1,'msg'=>'添加成功','data'=>"NULL"]);
        }else{
            return json(['code'=>0,'msg'=>'添加失败','data'=>"NULL"]);
        }

    }
}